package cn.fang2chen.java.distributed.lock.framework.redis;

import cn.fang2chen.java.distributed.lock.framework.RemoteLockParam;
import cn.fang2chen.java.distributed.lock.framework.RemoteLockSynchronizer;

/**
 * Redis 实现的远程锁
 *
 * @author dcmini chen
 * @since 1.0.0
 */
public class RedisRemoteLockSynchronizer implements RemoteLockSynchronizer {

    /**
     * redis 的客户端
     */
    private final RedisClient redisClient;

    public RedisRemoteLockSynchronizer(RedisClient redisClient) {
        this.redisClient = redisClient;
    }

    @Override
    public boolean tryAcquire( RemoteLockParam remoteLockParam) {
        return redisClient.setNxPx(remoteLockParam.getLockPath(), remoteLockParam.getOperatorId(), remoteLockParam.getExpiredTimeMilli());
    }

    @Override
    public boolean release( RemoteLockParam remoteLockParam) {
        return redisClient.delCas(remoteLockParam.getLockPath(), remoteLockParam.getOperatorId());
    }

    @Override
    public boolean isLocked( RemoteLockParam remoteLockParam) {
        return redisClient.hasValue(remoteLockParam.getLockPath());
    }

    @Override
    public long remainingTime( RemoteLockParam remoteLockParam) {
        return redisClient.timeRemaining(remoteLockParam.getLockPath());
    }

    @Override
    public boolean isOwner( RemoteLockParam remoteLockParam) {
        String value = redisClient.getValue(remoteLockParam.getLockPath());
        return remoteLockParam.getOperatorId().equals(value);
    }

}
